package offer

import (
	. "GoLeetcode/common"
)

/*
时间复杂度:O(MN) text1的长度M和text2的长度N
空间复杂度:O(MN)

构建一个二维dp,dp[i][j]表示text1[:i]和text2[:j]的最长公共子序列
1.如果text1[i] == text2[j]
	dp[i][j] = dp[i-1][j-1]+1
2.text1[i] != text2[j]
	dp[i][j] = max(dp[i-1][j], dp[i][j-1])
*/

func longestCommonSubsequence(text1 string, text2 string) int {
	m, n := len(text1), len(text2)
	dp := make([][]int, m+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
	}
	for i, c1 := range text1 {
		for j, c2 := range text2 {
			if c1 == c2 {
				dp[i+1][j+1] = dp[i][j] + 1
			} else {
				dp[i+1][j+1] = Max(dp[i+1][j], dp[i][j+1])
			}
		}
	}
	return dp[m][n]
}
